<?php

if (!defined('IN_ELS'))
{
    die('Hacking attempt');
}
class base {

	var $db;
	var $ip;
	var $view;
	/**
	 * basic
	 */
	function base() {
		$this->init_db();
		$this->init_template();
	}

	/**
	 * database
	 */
	function init_db() {
		require_once ELS_ROOT.'lib/db.class.php';
		$this->db = new db();
		$this->db->connect(UC_DBHOST, UC_DBUSER, UC_DBPW, UC_DBNAME, UC_DBCHARSET, UC_DBCONNECT, UC_DBTABLEPRE);
	}
	
	/**
	 * ip
	 */
	function init_ip() {
		require_once ELS_ROOT.'lib/ip.class.php';
		$this->ip = new ip();
	}
	
	/**
	 * template
	 */
	function init_template() {
		require_once ELS_ROOT.'lib/template.class.php';
		$this->view = new template();
	}
	/**
	 * redirect
	 */
	function pageRedirect($path){
		echo "<script>window.location='".$path."'</script>"; 
	}
	/**
	 * randomFilename
	 */
	function randomFilename(){
        $str = '';
        for($i = 0; $i < 9; $i++)
        {
            $str .= mt_rand(0, 9);
        }
        return time("data")."_" . $str;
    }
    
     /**
	 * dbInsert
	 */
	 function dbInsert($table,$data){
	 	 $sqlStr="INSERT INTO ".$table." SET ";
	 	 $num=0;
	 	 foreach($data as $k=>$d){
	 	 	 if($num==0){
	 	 	 	 $sign=" ";$num++;
	 	 	 }else{
	 	 	 	 $sign=" , ";
	 	 	 }
	 	 	 $sqlStr=$sqlStr.$sign.$k."='$d'";
	 	 }
	 	 $num++;
	 	 //echo $sqlStr;
	 	 return $this->db->query($sqlStr);
	 }
     /**
	 * dbUpdate
	 */
	 function dbUpdate($table,$data,$where){
	 	 $sqlStr="UPDATE ".$table." SET ";
	 	 $num=0;
	 	 foreach($data as $k=>$d){
	 	 	 if($num==0){
	 	 	 	 $sign=" ";$num++;
	 	 	 }else{
	 	 	 	 $sign=" , ";
	 	 	 }
	 	 	 $sqlStr=$sqlStr.$sign.$k."='$d'";
	 	 }
	 	 $sqlStr=$sqlStr." where ".$where;
	 	 $num++;
	 	 //echo $sqlStr;
	 	 return $this->db->query($sqlStr);
	 }
	 /**
	 * dbUpdate
	 */
	 function dbDelete($table,$where){
	 	 $sqlStr="DELETE FROM ".$table." where ".$where;
	 	 return $this->db->query($sqlStr);
	 }
	
	//******************************************************************************
	// function name:	CheckTableId
	// parameter	:	$TableName		Table name
	// return		:	New id 
	// memo			:	Create new primary key of table 
	//******************************************************************************
	function CheckTableId ($TableName){     
		$dataArray=$this->db->fetch_first("SELECT keynumber FROM table_key WHERE keyname = '$TableName'");
		if (empty($dataArray)){
			$d=array();
			$d['keynumber']=1;
			$d['keyname']=$TableName;
			$this->dbInsert('table_key',$d);
		  	return 1;
		} else {
			$dataArray['keynumber']=$dataArray['keynumber']+1;
			$this->dbUpdate("table_key",$dataArray,"keyname ='$TableName'");
		  	return $dataArray['keynumber'];
		}
	}
	
	/*
		名称：uploadFlash
		功能：上传flash文件
		备注：需要追加存在判断
	*/
	function uploadObject($file,$dir,$type,$name="null"){
		if($name=="null"){
			$dir_name=$this->randomFilename().".".$type;
		}else{
			$dir_name=$name.".".$type;
		}
		$dir=$dir.$dir_name;
		$upvalue = move_uploaded_file($file["tmp_name"],$dir);
		if (!$upvalue){
			return "";
		}else{
			return $dir_name;
		}
	}
	
	/*
		名称：uploadFlash
		功能：删除文件
		备注：需要追加存在判断
	*/
	function deleteFile($file){
		if(file_exists($file)){
			return unlink($file);
		}
		return false;
	}
	
	/**
	 * 加载相应的 Model, 存入 $_ENV 超级全局变量
	 * @param string $model 模块名称
	 * @param 该模块相对的基类 $base 默认为该基类
	 * @return 此处不需要返回
	 */
	function load($model, $base = NULL) {
		$base = $base ? $base : $this;
		if(empty($_ENV[$model])) {
			require_once ELS_ROOT."model/".$model."_model.php";
			eval('$_ENV[$model] = new '.$model.'base();');
		}
		return $_ENV[$model];
	}
	
	
	//******************************************************************************
	// function name:	replaceHtmlToAdditional
	// parameter	:	$htmlstr			Input HTML	
	// return		:  
	// memo			:	Conversion  HTML to additional of HTML
	//******************************************************************************
	function replaceHtmlToAdditional($htmlstr){
		$str = str_replace("&"        	, "&amp;"				, $htmlstr);
		$str = str_replace("<"      	, "&lt;"  				, $str);
		$str = str_replace(">"      	, "&gt;"  				, $str);
		$str = str_replace("'"     		, "&#39;" 				, $str);
		$str = str_replace("\""     	, "&quot;"				, $str);
		$str = str_replace("\r\n"     	, "<br>"				, $str);
		$str = str_replace("\n"     	, "<br>"				, $str);
		return $str;
	}
	
	function getCurrTimeLine(){
		$mtime = explode(' ', microtime());
		return $mtime[1];
	}
	
	function sgmdate($dateformat, $timestamp='', $format=0) {
		global $_SCONFIG, $_SGLOBAL;
		$_SCONFIG['timeoffset'] = 8;
		//取当前格林威治时间
		$curTime = strtotime(date('Y-m-d H:i:s'));
		if(empty($timestamp)) {
			$timestamp = $curTime;
		}
		$result = '';
		if($format) {
			$time = $curTime - $timestamp;
			if($time > 24*3600) {
				$result = gmdate($dateformat, $timestamp + $_SCONFIG['timeoffset'] * 3600);
			} elseif ($time > 3600) {
				$result = intval($time/3600)."小时前";
			} elseif ($time > 60) {
				$result = intval($time/60)."分钟前";
			} elseif ($time > 0) {
				$result = $time."秒前";
			} else {
				$result = "现在";
			}
		} else {
			$result = gmdate($dateformat, $timestamp + $_SCONFIG['timeoffset'] * 3600);
		}
		return $result;
	}

	//获取字符串
	function getstr($string, $length, $in_slashes=0, $out_slashes=0, $censor=0, $bbcode=0, $html=0) {
		global $_SC, $_SGLOBAL;
	
		$string = trim($string);
	
		if($in_slashes) {
			//传入的字符有slashes
			$string = $this->sstripslashes($string);
		}
		if($html < 0) {
			//去掉html标签
			$string = preg_replace("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $string);
			$string = $this->shtmlspecialchars($string);
		} elseif ($html == 0) {
			//转换html标签
			$string = $this->shtmlspecialchars($string);
		}
		if($censor) {
			//词语屏蔽
			@include_once('lib/data_censor.php');
			if($_SGLOBAL['censor']['banned'] && preg_match($_SGLOBAL['censor']['banned'], $string)) {
				showmessage('information_contains_the_shielding_text');
			} else {
				$string = empty($_SGLOBAL['censor']['filter']) ? $string :
					@preg_replace($_SGLOBAL['censor']['filter']['find'], $_SGLOBAL['censor']['filter']['replace'], $string);
			}
		}
		if($length && strlen($string) > $length) {
			//截断字符
			$wordscut = '';
			//strtolower:全部转换为小写字母，$_SC['charset']:在ucenter里已经写死就是utf-8
			$_SC['charset'] = 'utf-8';
			if(strtolower($_SC['charset']) == 'utf-8') {
				//utf8编码
				$n = 0;
				$tn = 0;
				$noc = 0;
				while ($n < strlen($string)) {
					$t = ord($string[$n]);
					if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
						$tn = 1;
						$n++;
						$noc++;
					} elseif(194 <= $t && $t <= 223) {
						$tn = 2;
						$n += 2;
						$noc += 2;
					} elseif(224 <= $t && $t < 239) {
						$tn = 3;
						$n += 3;
						$noc += 2;
					} elseif(240 <= $t && $t <= 247) {
						$tn = 4;
						$n += 4;
						$noc += 2;
					} elseif(248 <= $t && $t <= 251) {
						$tn = 5;
						$n += 5;
						$noc += 2;
					} elseif($t == 252 || $t == 253) {
						$tn = 6;
						$n += 6;
						$noc += 2;
					} else {
						$n++;
					}
					if ($noc >= $length) {
						break;
					}
				}
				if ($noc > $length) {
					$n -= $tn;
				}
				$wordscut = substr($string, 0, $n);
			} else {
				for($i = 0; $i < $length - 1; $i++) {
					if(ord($string[$i]) > 127) {
						$wordscut .= $string[$i].$string[$i + 1];
						$i++;
					} else {
						$wordscut .= $string[$i];
					}
				}
			}
			$string = $wordscut;
		}
		if($bbcode) {
			include_once('lib/function_bbcode.php');
			$string = bbcode($string, $bbcode);
		}
		if($out_slashes) {
			$string = $this->saddslashes($string);
		}
		return trim($string);
	}
	
	//去掉slassh
	function sstripslashes($string) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = $this->sstripslashes($val);
			}
		} else {
			$string = stripslashes($string);
		}
		return $string;
	}
	
	//取消HTML代码
	function shtmlspecialchars($string) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = $this->shtmlspecialchars($val);
			}
		} else {
			$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
				str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
		}
		return $string;
	}
	
	//SQL ADDSLASHES
	function saddslashes($string) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = $this->saddslashes($val);
			}
		} else {
			$string = addslashes($string);
		}
		return $string;
	}
	
	//写文件
	function writeCache($filename, $inputstr, $extra = "w"){
	    $handle = fopen($filename, $extra);
	    //$extra="w"文件不存在则创建
	    if (!$handle) {
	    	return false;
	    }else{
	        $writed = fwrite($handle, $inputstr);
	        if (!$writed) {
	        	return false;
	        }
	    }
	    @fclose($handle);
	    return true;
	}
	
	//数组处理
	function evalArray($array, $level = 0) {
		if(!is_array($array)) {
			return "'".$array."'";
		}
		foreach($array as $k => $v) {
			$array[$k] = str_replace("\r","",$array[$k]);
		}
		if(is_array($array) && function_exists('var_export')) {
			return var_export($array, true);
		}
	
		$space = '';
		for($i = 0; $i <= $level; $i++) {
			$space .= "\t";
		}
		$evaluate = "Array\n$space(\n";
		$comma = $space;
		if(is_array($array)) {
			foreach($array as $key => $val) {
				$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
				$val = !is_array($val) && (!preg_match("/^\-?[1-9]\d*$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
				if(is_array($val)) {
					$evaluate .= "$comma$key => ".$this->evalArray($val, $level + 1);
				} else {
					$evaluate .= "$comma$key => $val";
				}
				$comma = ",\n$space";
			}
		}
		$evaluate .= "\n$space)";
		return $evaluate;
	}
		//图片缩放
	function resizeImage($im,$maxwidth,$maxheight,$name,$filetype="")
	{
	    $pic_width = @imagesx($im);
	    $pic_height = @imagesy($im);

	    if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
	    {
	        if($maxwidth && $pic_width>$maxwidth)
	        {
	            $widthratio = $maxwidth/$pic_width;
	            $resizewidth_tag = true;
	        }

	        if($maxheight && $pic_height>$maxheight)
	        {
	            $heightratio = $maxheight/$pic_height;
	            $resizeheight_tag = true;
	        }

	        if($resizewidth_tag && $resizeheight_tag)
	        {
	            if($widthratio<$heightratio)
	                $ratio = $widthratio;
	            else
	                $ratio = $heightratio;
	        }

	        if($resizewidth_tag && !$resizeheight_tag)
	            $ratio = $widthratio;
	        if($resizeheight_tag && !$resizewidth_tag)
	            $ratio = $heightratio;

	        $newwidth = $pic_width * $ratio;
	        $newheight = $pic_height * $ratio;

	        if(function_exists("imagecopyresampled"))
	        {
	            $newim = @imagecreatetruecolor($newwidth,$newheight);
	           @imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
	        }
	        else
	        {
	            $newim = @imagecreate($newwidth,$newheight);
	           @imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
	        }
			
			if($filetype){
				$name = $name.$filetype;
			} else {
				$name = $name;
			}
	        @imagejpeg($newim,$name);
	        @imagedestroy($newim);
	    }
	    else
	    {
	        if($filetype){
				$name = $name.$filetype;
			} else {
				$name = $name;
			}
	        @imagejpeg($im,$name);
	    }           
	}
		//上传图片共通函数
	function uploadImage($img_name,$files_name,$file_dir,$file_err){
		//$img_name:上传文件名称;$files_name文件名;$file_dir保存路径;$file_err:错误变量
		list($picture_name, $picture_ext) = split('\.', $img_name);
		if(strtolower($picture_ext) == "jpg" || strtolower($picture_ext) == "gif" ){
			$picture_name = $this->uploadObject($files_name,ELS_ROOT.$file_dir,strtolower($picture_ext));
			if($picture_name == ""){
				$errCode = $files_name['error'];
				if($errCode == 1 || $errCode == 2){
					$this->view->assign($file_err  ,"图片文件太大");
					$hasError = true;
				}elseif($errCode == 4){
					$this->view->assign($file_err  ,"图片上传失败");
					$hasError = true;
				}elseif($errCode == 3){
					$this->view->assign($file_err  ,"图片上传被切断");
					$hasError = true;
				}
				return $hasError;
			} else {
				return $picture_name;
			}
		}else{
			if($img_name){
				$this->view->assign($file_err  ,"图片只能使用jpg或者gif格式");
				$hasError = true;
			} else {
				$hasError = false;
			}
			return $hasError;
		}
	}
}

?>